package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.constant.TokenConstant;
import com.itheima.domian.PhoneCode;
import com.itheima.domian.User;
import com.itheima.domian.vo.UserVo;
import com.itheima.mapper.client.UserMapper;
import com.itheima.service.client.UserService;
import com.itheima.utils.RandomCodeUtils;
import com.itheima.utils.SendMessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @Author 12441
 * @Date 2022/8/18 14:52
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;


    @PostMapping("/sendMsg")
    public R<String>sendMsg(@RequestBody User user, HttpServletRequest httpServletRequest){

        //判断是否输入了手机号
        String phone = user.getPhone();

        if (phone==null){

            return R.error("短信发送错误");
        }
        //生成随机4位数验证码
        String securityCode = RandomCodeUtils.getSecurityCode(4,
                RandomCodeUtils.SecurityCodeLevel.Simple,
                false);

        log.info("==============验证码为:",securityCode);

        //发送短信
        SendMessageUtils utils = new SendMessageUtils();
        utils.sendMessage(securityCode);


        //讲验证码存入到redis，验证码有效2分钟
        redisTemplate.opsForValue().set(phone,securityCode,120, TimeUnit.SECONDS);



        return R.success("手机验证短信发送成功");
    }

    @PostMapping("/login")
    public R<UserVo>login(@RequestBody PhoneCode phoneCode){

        String phone = phoneCode.getPhone();
        String code = phoneCode.getCode();


        if (phone==null){

            return R.error("请输入手机号");
        }
        if (code==null){

            return R.error("请输入验证码");
        }

        String  securityCode= (String) redisTemplate.opsForValue().get(phone);


        log.info("==============验证码为:{}",securityCode);

        //判断

        if (securityCode.equals(code)==false){
            return R.error("登录失败");
        }
        //验证成功，存入缓存，讲User对象
        User user = new User();

        user.setPhone(phone);

        userService.save(user);

        String tokenString = System.currentTimeMillis() + user.getPhone();
        String jsonString = JSON.toJSONString(user);
        //加密token
        String token = String.valueOf(DigestUtils.md5Digest(tokenString.getBytes(StandardCharsets.UTF_8)));

        redisTemplate.opsForValue().set(TokenConstant.USER_TOKEN_PREFIX+token,jsonString,
                1, TimeUnit.DAYS);

        UserVo userVo= new UserVo();
        userVo.setToken(token);
        BeanUtils.copyProperties(user, userVo);

        return R.success(userVo,"登录成功");
    }

    @PostMapping("/loginout")
    public R<String> logout(@RequestHeader("AuthorizationUser") String token) {


        //删除token
        redisTemplate.delete(TokenConstant.USER_TOKEN_PREFIX + token);

        //显示给前端的
        return R.success("l");
    }
//    @GetMapping("/page")
//    public R<MyPage> page(HttpServletRequest httpServerRequest){
//
//        MyPage myPage = new MyPage();
//
//        String name = httpServerRequest.getParameter("name");
//        Integer page = Integer.valueOf(httpServerRequest.getParameter("page"));
//        Integer size = Integer.valueOf(httpServerRequest.getParameter("pageSize"));
//
//
//        IPage ipage=new Page(page,size);
//
//        userMapper.selectPage(ipage,null);
//
//        //查询数据ipage.getRecords();
//        long total = ipage.getTotal();
//        if (total==0){
//
//            return R.error("无数据");
//        }
//        myPage.setRecords(ipage.getRecords());
//        myPage.setTotal(ipage.getTotal());
//        myPage.setSize(size);
//        myPage.setCurrent(page);
//        return R.success(myPage,"查询完成");
//
//    }
//
//    @GetMapping("/{id}")
//    public R<User> selectById(@PathVariable int id ) {
//
//        //根据页面提交的用户名username查询数据库
//        User employees = userMapper.selectById(id);
//
//        return R.success(employees,"登录成功！");
//    }
//    @PostMapping
//    public R<String> addUser(@RequestBody User employees) {
//        //初始化新用户密码
//        employees.setPassword("1234");
//
//
//        String sex = employees.getSex();
//        if (sex.equals("1")){
//            employees.setSex("男");
//        }
//        else {
//            employees.setSex("女");
//        }
//
//        userMapper.addUser(employees);
//
//        return R.success("退出成功");
//    }
//
//    @PutMapping
//    public R<User> update(@RequestBody User employees){
//        Integer status = employees.getStatus();
//        log.info("----------"+ status);
//        if (status==0){
//            status=0;
//        }
//        else {
//            status=1;
//        }
//        employees.setStatus(status);
//        userMapper.updateById(employees);
//        return R.success(employees,"修改成功");
//    }

}